#include "udp_get.h"

#include "face.h"
#include "ui_face.h"


face::Udp_get()
{

    udpSocket = new QUdpSocket(this);
    // 绑定端口，监听所有地址上的数据
    if (udpSocket->bind(QHostAddress("192.168.137.1"), 8004)) {
        qDebug() << "UDP端口 8004";
    } else {
        qDebug() << "UDP 绑定失败";
        return;
    }

  connect(udpSocket,&QUdpSocket::readyRead,this,&Udp_get::readPendingDatagrams);

}

void Udp_get::resizeEvent(QResizeEvent *event)
{

}

void Udp_get::readPendingDatagrams()
{
        // 循环读取所有可用数据包
        while (udpSocket->hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(udpSocket->pendingDatagramSize());

            QHostAddress sender;
            quint16 senderPort;

            // 接收数据包
            udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
            ui->label_video->setAlignment(Qt::AlignCenter);

            // 将QByteArray转换为QImage
            QImage image;
            if (image.loadFromData(datagram)) {
                // 将QImage转换为QPixmap并设置到QLabel上
                QLabel label;
                QPixmap pixmap = QPixmap::fromImage(image);
                ui->label_video->setPixmap(pixmap);
                ui->label_video->show();
                qDebug() << "load image from data.";
            } else {
                // 如果图片加载失败，输出错误信息
                qDebug() << "Failed to load image from data.";
            }

          //  qDebug() << "Home Received data:" << datagram;
            qDebug() << "From:" << sender.toString() << ":" << senderPort;
        }
}
